package com.example.hosptial.newController;

import com.example.hosptial.model.enity.Patient;
import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.service.PatientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 我的患者管理Controller
 * 处理医生查看和管理其负责的患者信息的请求
 */
@Controller
@RequestMapping("/doctor/my-patients")
public class MyPatientsController {

    private static final Logger logger = LoggerFactory.getLogger(MyPatientsController.class);

    @Autowired
    private PatientService patientService;

    /**
     * 显示我的患者列表页面
     */
    @GetMapping
    public String showMyPatientsPage(HttpSession session) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return "redirect:/doctor/auth/login";
        }
        return "doctor/my-patients";
    }

    /**
     * 获取患者列表（AJAX调用）
     */
    @GetMapping("/list")
    @ResponseBody
    public ResponseEntity<?> getPatientsList(
            HttpSession session,
            @RequestParam(required = false) String searchName) {
        
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).body("未登录或会话已过期");
        }

        try {
            logger.info("正在获取医生 {} 的病人列表", doctor.getDoctorId());
            
            List<Patient> patients;
            if (searchName != null && !searchName.trim().isEmpty()) {
                logger.info("使用搜索条件: {}", searchName);
                patients = patientService.searchPatientsByName(doctor.getDoctorId(), searchName);
            } else {
                patients = patientService.getPatientsByDoctor(doctor.getDoctorId());
            }
            
            logger.info("找到 {} 个病人", patients.size());
            
            // 构建简化的响应对象
            List<Map<String, Object>> simplifiedPatients = patients.stream()
                .map(patient -> {
                    Map<String, Object> patientMap = new HashMap<>();
                    patientMap.put("patientId", patient.getPatientId());
                    patientMap.put("patientName", patient.getPatientName());
                    patientMap.put("patientGender", patient.getPatientGender());
                    patientMap.put("patientAge", patient.getPatientAge());
                    patientMap.put("patientPhone", patient.getPatientPhone());
                    return patientMap;
                })
                .collect(java.util.stream.Collectors.toList());

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", simplifiedPatients);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取患者列表失败: {}", e.getMessage(), e);
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取患者列表失败");
            errorResponse.put("error", e.getMessage());
            
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 获取患者详细信息（AJAX调用）
     */
    @GetMapping("detail/{patientId}")
    @ResponseBody
    public ResponseEntity<?> getPatientDetail(
            HttpSession session,
            @PathVariable Integer patientId) {

        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).body(Map.of(
                "code", 401,
                "message", "未登录或会话已过期"
            ));
        }

        try {
            logger.info("正在获取病人ID为 {} 的详细信息", patientId);
            
            // 获取病人详细信息
            Map<String, Object> patientDetail = patientService.getPatientDetail(patientId);
            
            // 检查是否是当前医生的病人
            String patientDoctorId = (String) patientDetail.get("doctorId");
            if (!doctor.getDoctorId().equals(patientDoctorId)) {
                return ResponseEntity.status(403).body(Map.of(
                    "code", 403,
                    "message", "无权查看该病人信息"
                ));
            }

            // 构建病房信息
            Map<String, Object> wardInfo = new HashMap<>();
            wardInfo.put("floorNum", patientDetail.get("floorNum"));
            wardInfo.put("wardNum", patientDetail.get("wardNum"));
            wardInfo.put("bedNum", patientDetail.get("bedNum"));

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("patientId", patientDetail.get("patientId"));
            responseData.put("patientName", patientDetail.get("patientName"));
            responseData.put("patientGender", patientDetail.get("patientGender"));
            responseData.put("patientAge", patientDetail.get("patientAge"));
            responseData.put("patientPhone", patientDetail.get("patientPhone"));
            responseData.put("patientIdCard", patientDetail.get("patientIdCard"));
            responseData.put("conditionDesc", patientDetail.get("conditionDesc"));
            responseData.put("beginTime", patientDetail.get("beginTime"));
            responseData.put("wardInfo", wardInfo);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", responseData);
            
            logger.info("成功获取病人详情");
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException e) {
            logger.warn("获取病人详情失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of(
                "code", 400,
                "message", e.getMessage()
            ));
        } catch (Exception e) {
            logger.error("获取病人详情失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "获取病人详情失败"
            ));
        }
    }

    /**
     * 搜索患者（AJAX调用）
     */
    @GetMapping("/search")
    @ResponseBody
    public ResponseEntity<?> searchPatients(
            HttpSession session,
            @RequestParam String searchName) {

        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return ResponseEntity.status(401).body("未登录或会话已过期");
        }

        try {
            List<Patient> patients = patientService.searchPatientsByName(doctor.getDoctorId(), searchName);
            return ResponseEntity.ok(patients);
        } catch (IllegalArgumentException e) {
            logger.warn("搜索患者失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("搜索患者失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("搜索患者失败");
        }
    }
}